//
//  ICServeMessageViewController.m
//  ICome
//
//  Created by zhangrongwu on 2016/11/29.
//  Copyright © 2016年 iCom. All rights reserved.
//

#import "ICServeMessageViewController.h"
#import "ICMessageTableViewCell.h"
#import "ICActionSheetView.h"
#import "ICMessageNetworkManager.h"
#import "ICHeaderFile.h"

@interface ICServeMessageViewController()<UITableViewDataSource, UITableViewDelegate, ICActionSheetViewDelegate>

@property (nonatomic, strong)UITableView *tableView;
@property (nonatomic, strong)NSMutableArray *dataArray;
@property (nonatomic, strong)ICActionSheetView *actionSheet;
@property (nonatomic, strong)UIButton *rightButton;

@end

@implementation ICServeMessageViewController
#pragma mark - view load

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setNav];
    [self setUI];
    [self initNotificationCenter];
}


- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self reloadDataSource];
}

// 刷新数据源
- (void)reloadDataSource
{
    NSMutableArray *dataList = [[NSMutableArray alloc] init];
    WEAKSELF
    [ICMessageDatabase selectGroupsIsTop:NO gType:[NSString stringWithFormat:@"%d", ICGroup_ROBOT] finish:^(NSArray *array, NSError *error) {
        if (array.count > 0) { // 获取的组中 存在一个自己的组需要去除
            [dataList addObjectsFromArray:array];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.dataArray removeAllObjects];
            [weakSelf.dataArray addObjectsFromArray:dataList];
            [weakSelf.tableView reloadData];
            [self updateGroupUnreadMessageCount];
        });
    }];
}

- (void)initNotificationCenter {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(messageDidReceived:) name:NotificationReceiveMessage object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(backAction:) name:@"SERVEDELEACTION" object:nil];
}

- (void)messageDidReceived:(NSNotification *)notifi
{
    NSDictionary *dic  = notifi.object;
    NSString *to = [dic objectForKey:@"to"];
    if (![ICTools stringEmpty:to]) {
        if ([to hasPrefix:@"rbt_"]) {
            WEAKSELF
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [weakSelf reloadDataSource];
            });
        }
    }
}
// 接收到返回首页
- (void)backAction:(NSNotification *)notifi {
    [self.navigationController popToRootViewControllerAnimated:YES];
}

- (void)updateGroupUnreadMessageCount {
    int unreadCount = 0;
    for (ICGroup *group in self.dataArray) {
        unreadCount = unreadCount + group.unReadCount;
    }
    NSString *svrId = [NSString stringWithFormat:@"svr_%@", [ICUser currentUser].eId];
    [ICMessageDatabase updateGroupUnreadMessageCountWithGroupId:svrId count:unreadCount];
}


- (void)ActionSheetView:(ICActionSheetView *)actionSheetView clickedButtonAtIndex:(NSInteger)buttonIndex {
    NSInteger status = 1;
    if (buttonIndex == 0) {
        status = 1;
    } else if (buttonIndex == 1) {
        status = 2;
    }
    NSDictionary *parma = @{@"eId":[ICUser currentUser].eId,
                            @"status":@(status)};
    [[ICMessageNetworkManager sharedInstance] customerChangeStatus:parma success:^(id object) {
        ALERT(@"状态修改成功");
        NSString *title = @"在线";
        if (buttonIndex == 0) {
            title = @"在线";
        } else if (buttonIndex == 1) {
            title = @"离线";
        }
        [self.rightButton setTitle:title forState:UIControlStateNormal];
        [[NSUserDefaults standardUserDefaults] setObject:title forKey:[NSString stringWithFormat:@"%@_serve_status", [ICUser currentUser].eId]];
    } failure:^(NSError *error) {
        ALERT(@"修改失败");
    }];
}

- (void)rightButtonAction:(UIButton *)sender {
    [self.actionSheet showInView:[ICTools lastWindow].rootViewController.view];
}

#pragma mark - UI
- (void)setNav {
    self.title = @"平台客服";
    
    
    NSString *statusTitle = [[NSUserDefaults standardUserDefaults] objectForKey:[NSString stringWithFormat:@"%@_serve_status", [ICUser currentUser].eId]];
    self.rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.rightButton setTitle:statusTitle == nil ? @"在线" : statusTitle forState:UIControlStateNormal];
    [self.rightButton setTitleEdgeInsets:UIEdgeInsetsMake(0, -20, 0, 0)];
    [self.rightButton setImage:[UIImage imageNamedFromiComeSDKBundle:@"icon_open_down_white"] forState:UIControlStateNormal];
    [self.rightButton setImageEdgeInsets:UIEdgeInsetsMake(0, 45, 0, 0)];
    self.rightButton.width = 60;
    self.rightButton.height = 50;
    self.rightButton.titleLabel.font = [UIFont systemFontOfSize:17];
    [self.rightButton setTitleColor:DEFAULT_SUBJECT_COLOR forState:UIControlStateNormal];
    [self.rightButton addTarget:self action:@selector(rightButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *barItem = [[UIBarButtonItem alloc] initWithCustomView:self.rightButton];
    [self.navigationItem setRightBarButtonItem:barItem];
}

- (void)setUI {
    self.tableView.backgroundColor = BACKGROUNDCOLOR;
    [self.tableView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_top);
        make.left.equalTo(self.view.mas_left);
        make.bottom.equalTo(self.view.mas_bottom);
        make.right.equalTo(self.view.mas_right);
    }];
}

#pragma mark - tableViewDelegate
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ICMessageTableViewCell *cell = [ICMessageTableViewCell cellWithTableView:tableView];
    if (indexPath.row == self.dataArray.count - 1) {
        [cell setBottomLineStyle:CellLineStyleNone];
    }
    else {
        [cell setBottomLineStyle:CellLineStyleDefault];
    }
    cell.group = self.dataArray[indexPath.row];
    return cell;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 70;
}


- (NSArray *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString *topTitle ,*readTitle;
    ICGroup *group  = self.dataArray[indexPath.row];
    topTitle  = group.isTop ? @"取消置顶" : @"置顶";
    readTitle = group.unReadCount ?  @"标记未读" : @"标记已读";
    //设置删除按钮
    UITableViewRowAction * deleteRowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"删除" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
        [self deleteLocalGroup:indexPath];
    }];
    //置顶
    UITableViewRowAction * topRowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:topTitle handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
        [self setTopCellWithIndexPath:indexPath currentTop:group.isTop];
    }];
    //标记已读
    UITableViewRowAction * collectRowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:readTitle handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
        [self markerReadWithIndexPath:indexPath currentUnReadCount:group.unReadCount];
    }];
    collectRowAction.backgroundColor = [UIColor grayColor];
    topRowAction.backgroundColor     = [UIColor orangeColor];
    return  @[deleteRowAction,topRowAction,collectRowAction];
}


- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return NO;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    ICGroup *group = self.dataArray[indexPath.row];
    
    ICChatViewController *chatVc = [[ICChatViewController alloc] init];
    chatVc.group                 = group;
    [self.navigationController pushViewController:chatVc animated:YES];
    [ICMessageHelper updateGroupReadWithGroupId:group.gId];
}


#pragma mark - private
// 标记已读
- (void)markerReadWithIndexPath:(NSIndexPath *)indexPath currentUnReadCount:(int)unReadCount
{
    ICMessageTableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
    [ICMessageDatabase updateGroupUnreadMessageCountWithGroupId:cell.group.gId count:unReadCount > 0 ? 0 : 1];
    ICGroup * group              = self.dataArray[indexPath.row];
    group.unReadCount            = unReadCount > 0 ? 0 : 1;
    [self.tableView reloadRowAtIndexPath:indexPath withRowAnimation:UITableViewRowAnimationNone];
}

- (void)setTopCellWithIndexPath:(NSIndexPath *)indexPath
                     currentTop:(BOOL)isTop
{
    ICMessageTableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
    [ICMessageDatabase makeGroupTop:cell.group isTop:!isTop lastMsgTime:[ICMessageHelper currentMessageTime]];
    // 数据源改变
    [self reloadDataSource];
}

- (void)deleteLocalGroup:(NSIndexPath *)indexPath
{
    ICGroup *group = self.dataArray[indexPath.row];
    [ICMessageDatabase changeGroupLocalType:0 GroupId:group.gId];
    [self.dataArray removeObjectAtIndex:indexPath.row];
    [self.tableView deleteRowAtIndexPath:indexPath withRowAnimation:UITableViewRowAnimationFade];
}



#pragma mark - setter and getter

- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        [self.view addSubview:_tableView];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    }
    return _tableView;
}


- (NSMutableArray *)dataArray
{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return  _dataArray;
}

-(ICActionSheetView *)actionSheet {
    if (!_actionSheet) {
        _actionSheet = [[ICActionSheetView alloc] initWithTitles:@[@"在线",@"离线"] delegate:self cancelButtonTitle:@"取消"];
    }
    return _actionSheet;
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


@end
